package com.zrrd.yunchmall.user.controller;

import com.zrrd.yunchmall.pojo.UserTmp;
import com.zrrd.yunchmall.user.service.UserServiceImpl;
import com.zrrd.yunchmall.user.util.JwtUtil;
import com.zrrd.yunchmall.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author yekong
 */
@RestController
@RequestMapping("/user")
//@Api添加在controller类上
@Api(tags = "用户服务接口", value = "用户服务接口")
@SuppressWarnings("all")
public class UserController{

    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/detail/{uid}")
    //@ApiOperation加在请求处理方法上，其中httpMethod属性默认可不写
    @ApiOperation(value = "查询用户详情", httpMethod = "GET")
    //@ApiParam加在请求参数上, value属性指定名称， required = true属性为必要参数
    public UserTmp detail(@ApiParam(name = "uid", value = "用户ID",required = true) @PathVariable("uid") int uid) {
        return userService.getById(uid);
    }


    //http://localhost:8061/user/login?username=admin&password=123456
    @RequestMapping("/login")
    @ApiOperation(value = "用户登录", httpMethod = "POST")
    //POST请求中参数默认为body类型，通过在参数前增加@RequestParam告诉请求这是参数
    public ResponseResult<String> login(@ApiParam(name = "username", value = "用户名", required = true)
                                                    @RequestParam String username,
                                        @ApiParam(name = "password", value = "密码", required = true)
                                                    @RequestParam String password) {
        String token = userService.login(username, password);
        if (token != null) {
            return new ResponseResult<>(200,"登陆成功",token);
        }else {
            return new ResponseResult<>(401,"用户名或密码错误", null);
        }
    }

    @RequestMapping("/login2")
    @ApiOperation(value = "用户登录2", httpMethod = "POST")
    public ResponseResult<String> login2(@ApiParam(required = true) @RequestBody UserTmp userTmp) {
        String token = userService.login(userTmp.getUsername(), userTmp.getPassword());
        if (token != null) {
            return new ResponseResult<>(200,"登陆成功",token);
        }else {
            return new ResponseResult<>(401,"用户名或密码错误", null);
        }
    }

    @RequestMapping("/auth")
    public UserTmp auth(String token) {
        //去掉token前面的Bearer + 空格
        return JwtUtil.parse(token.substring(7));
    }
}
